const over = document.getElementsByClassName('over')[0];
const f = document.querySelector('.jifeng span');
class Game {
    constructor() {
        this.sky = new Sky();
        this.land = new Land();
        this.bird = new Bird();
        this.pipe = new ChuangJian();
        this.timer = null;
        this.jianGe = 16;
        this.shiJian = this.jianGe / 1000;
        this.gameOver = false;
        this.fengShu = 0;
    }

    start() {
        if (this.timer) {
            return;
        }
        this.timer = setInterval(() => {
            this.sky.move(this.shiJian);
            this.land.move(this.shiJian);
            this.bird.move(this.shiJian);
            this.bird.start();
            this.pipe.start();
            this.pipe.move(this.shiJian);
            this.jifeng();
            if (this.isGameOver()) {
                this.gameOver = true;
                this.stop();
                over.style.display = 'block';
            }
        }, this.jianGe);
    }

    stop() {
        clearInterval(this.timer);
        this.bird.stop();
        this.pipe.stop();
        this.timer = null;
    }

    jifeng() {
        for (let i = 0; i < this.pipe.pipes.length; i++) {
            if (this.bird.left > this.pipe.pipes[i].upPipe.left && !this.pipe.pipes[i].upPipe.isJiFeng) {
                console.log(this.bird.left, this.pipe.pipes[i].upPipe.left)
                this.fengShu++;
                this.pipe.pipes[i].upPipe.isJiFeng = true;
                f.innerHTML = this.fengShu;
            }
        }
    }

    isGameOver() {
        if (this.bird.top >= this.bird.maxTop) {
            return true;
        }
        for (let i = 0; i < this.pipe.pipes.length; i++) {
            if (this.isCrash(this.bird, this.pipe.pipes[i].upPipe) ||
                this.isCrash(this.bird, this.pipe.pipes[i].downPipe)) {
                return true;
            }
        }
        return false;
    }

    isCrash(ju1, ju2) {
        const ju1X = ju1.left + (ju1.width / 2);
        const ju1Y = ju1.top + (ju1.height / 2);
        const ju2X = ju2.left + (ju2.width / 2);
        const ju2Y = ju2.top + (ju2.height / 2);
        const x = Math.abs(ju1X - ju2X);
        const y = Math.abs(ju1Y - ju2Y);
        if (x < (ju1.width + ju2.width) / 2 && y < (ju1.height + ju2.height) / 2) {
            return true;
        }
        return false;
    }

    bindEvend() {
        window.onkeydown = (e) => {
            // console.log(e);
            if (e.key === 'Enter') {
                if (this.gameOver) {
                    window.location.reload();
                }
                if (this.timer) {
                    this.stop();
                } else {
                    this.start();
                }
            } else if (e.key === ' ') {
                this.bird.jump();
            }
        }
    }

}

var g = new Game();
g.bindEvend();